package com.itheima.controller;

import com.itheima.pojo.Blog;
import com.itheima.service.BlogService;
import com.itheima.utils.PageResult;
import com.itheima.utils.Result;
import com.itheima.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @PostMapping("/add")
    public Result add(@RequestBody Blog blog) {
        try {
            blogService.add(blog);
            return new Result(StatusCode.SUCCESS, "插入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.FAIL, "插入失败");
        }
    }

    @PutMapping("/edit")
    public Result edit(@RequestBody Blog blog) {
        try {
            blogService.edit(blog);
            return new Result(StatusCode.SUCCESS, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.FAIL, "更新失败");
        }
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestBody Blog blog) {
        try {
            blogService.delete(blog);
            return new Result(StatusCode.SUCCESS, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.FAIL, "删除失败");
        }
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Blog> list) {
        try {
            blogService.deleteBatch(list);
            return new Result(StatusCode.SUCCESS, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.FAIL, "删除失败");
        }
    }

    @GetMapping("/getList")
    public Result getList(@RequestBody Blog blog) {
        try {
            if (blog.getCurrentPage() == null || blog.getPageSize() == null) {
                throw new RuntimeException("currentPage和pageSize都不能为空");
            }
            PageResult<Blog> pageResult= blogService.getList(blog);
            return new Result(StatusCode.SUCCESS, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.FAIL, "查询失败");
        }
    }
}
